function try_chg_advert_form()
{
  chg_advert_form();check_total_price();
}
/**
 * dinamical change advert form fields
 */
function d2date(d)
{
    var dd=d.split('/');
    return new Date(dd[2],(dd[0]-1),dd[1],'00','00');
}
function chg_advert_form()
{
  if(jQuery('#field_private_status input:checked').val()=='bussiness')
  {    
    jQuery('#price_private').hide(); 
   jQuery('#price_bussiness').show();  
   jQuery('#price_buy').hide();
  jQuery('#taxonomy_box').hide();
   jQuery('#taxonomy_box1').show();   
   jQuery('#personal_name').hide(); 
   jQuery('#bussiness_name').show();
   jQuery('#company_name').show();
  }else{
    jQuery('#field_www_box').hide();     
  jQuery('#price_bussiness').hide();
  jQuery('#price_private').show();   
   jQuery('#price_buy').hide();
    jQuery('#taxonomy_box').show();
   jQuery('#taxonomy_box1').hide();   
   jQuery('#personal_name').show(); 
   jQuery('#bussiness_name').hide();
   jQuery('#company_name').hide();
  }    
}
/**
 *remove public date
 */
function remove_date(id)
{

var o=document.getElementById(id);
document.getElementById("pub_dates").removeChild(o);
if(jQuery('#period_place_day').html()!=null)
{

count_public_days();
check_total_price();

$("#dates_box").datepicker( "option", "beforeShowDay", function(date) {var id=prep_month(date.getDate())+'/'+prep_month(date.getMonth()+1)+'/'+date.getFullYear();

if(document.getElementById(id)!=null){return [2,"blue"];}
else if(date.toString().indexOf("Sun ")!=-1)
return [1,"red"];
else return [1];});
}
  
}
function _body_too_long(delta,chars)
{
document.getElementById('body_counter').style.border='solid red 1px';
document.getElementById('body_counter_msg').innerHTML='Длина сообщения превысила <b>'+chars+'</b>, цена будет умноженна на <b>'+delta+'</b>';
document.getElementById('body_counter_msg').className='body_msg';
}
function _body_ok()
{
document.getElementById('body_counter').style.border='none';
document.getElementById('body_counter_msg').innerHTML='';
document.getElementById('body_counter_msg').className='';
}
function count_body_text(val)
{
  
  
  var c=val.length;
  var last_element;
  var last_j;
  for(var j=0;j<count_limits.length;j++)
  {
    if(c>(count_limits[j]))
    {
      //draw_message
      _body_too_long(j+1,count_limits[j]);
      
      
    }/*else  */
    last_element=count_limits[j];
    last_j=j;
  }
  
  
  if((c<count_limits[1])&&(document.getElementById('body_counter_msg').className=='body_msg'))
    {
      _body_ok();
    }
  if(c>(last_element-1))
  {
    //remove sper
    
    document.getElementById("body").value=document.getElementById("body").value.substr(0,(last_element));
    _body_too_long(last_j,count_limits[j-2]);
    c=document.getElementById("body").value.length;
    
  }
  document.getElementById('body_counter').value=c;
  check_total_price();
  
}
function count_public_days()
{
  var period=document.getElementById('period').value;
  
  var count_dates=document.getElementById('pub_dates').getElementsByTagName('input').length;
  
  if(document.getElementById('count_public_dates')!=null)document.getElementById('count_public_dates').innerHTML=count_dates;
  
  if(document.getElementById('period_place_day')!=null)document.getElementById('period_place_day').innerHTML=period-count_dates;
  
  return (period-count_dates);
}
var public_dates=new Array;
var public_dates_cp=new Array;
function create_public_date_before(d,nodeafter)
{
  
if(document.getElementById(d)==null)
{
  
  var div=document.createElement("div");
  div.id=d;
  div.className="advert_date_row";
  div.innerHTML=prep_human_day(d)+' <input type="hidden" name="pub_dates[]" value="'+d+'"><a href="javascript://" onClick="remove_date(\''+d+'\')">убрать</a>';
  
  //document.getElementById("pub_dates").appendChild(div);

  document.getElementById("pub_dates").insertBefore(div,document.getElementById(nodeafter));
} 
}
function create_public_date(d)
{
  
  if(document.getElementById(d)==null)
  {
  var div=document.createElement("div");
  div.id=d;
  div.className="advert_date_row";
  div.innerHTML=prep_human_day(d)+' <input type="hidden" name="pub_dates[]" value="'+d+'"><a href="javascript://" onClick="remove_date(\''+d+'\')">убрать</a>';
  
  document.getElementById("pub_dates").appendChild(div);
  
  }
}
function _chk_slot_date(d)
{
  var tids=new Array;
    jQuery('#loaded_taxonomy li').each(function(){
    tids[tids.length]=this.className.substr(2);
    
  });
  var inputs=document.getElementById('taxonomy_box').getElementsByTagName('input');
  
  var url='/bt-form/callback/advert_date/';
  
  var nid=document.getElementById("nid").value;
  
  $.ajax({
type: "POST",
url: url,
data: { d: d, tids: tids.join(","),nid:nid}
}).done(function( msg ) {
if(msg=='<div>0</div>')
{
  alert('Извините на эту дату '+d+' уже забронированно более 4-х рекомендованных обьявлений, попробуйте другие даты или рубрики'); 
  remove_date(d);
  
}
});
  
}
function add_public_date(d,flg)
{
if(flg==null)flg='new';

if(document.getElementById(d)==null)
{
  
var res=count_public_days();

if(res)
{
  if(flg=='new')_chk_slot_date(d);

  var inputs=document.getElementById("pub_dates").getElementsByTagName('input');
  var last=false;
  if(inputs.length>0)
  {//already have dates  
  for(var i=0;i<inputs.length;i++)
  {
    if(d!=inputs[i].value)
    {
    
      if((c_string2date(d)<c_string2date(inputs[i].value))&&(d!=inputs[i].value))
      {
      create_public_date_before(d,inputs[i].value);
      last=true;
      break;
      }
    }
  }
  if(last==false){create_public_date(d);}
  
    
  }else{
    //first date!!
    
      
      if(flg=='new')
      {
	var per=document.getElementById('period').value-1;
     var s=(c_string2date(d)+((per+1)*24*3600));
      
      for(var a=c_string2date(d);a<s;a+=24*3600)
      {
	var new_date=new Date;
	new_date.setTime((a*1000));
	create_public_date(prep_month(new_date.getDate())+'/'+prep_month(new_date.getMonth()+1)+'/'+new_date.getFullYear());
      }
	
      }else{
	
	create_public_date(d);
	
      }
      /*
      
    */
  }
count_public_days();

}
}else{
  remove_date(d);
}
}
function c_string2date(d)
{

  var ar=d.split('/');

  var result=parseInt(new Date(ar[2]+'/'+ar[1]+'/'+ar[0]).getTime()/1000);
  //return new Date(ar[2]+'-'+ar[1]+'-'+ar[0]);

  return result;
}
function c_string2dateunix(d)
{

  var ar=d.split('/');
  return parseInt(new Date(ar[2]+'-'+ar[1]+'-'+ar[0]).getTime()/1000);
  //return new Date(ar[2]+'-'+ar[1]+'-'+ar[0]);
}

function prep_month(m)
{
  m+='';
  
  if(m.length==1)m='0'+m;
  return m;
}

function prep_human_day(d)
{
  var day_array=d.split("/");
  var russian_month=Array('none','Январь','Февраль','Март','Апрель','Май','Июнь','Июль','Август','Сентябрь','Октябрь','Ноябрь','Декабрь');
  var russian_week=Array('Воскресенье', 'Понедельник', 'Вторник', 'Среда', 'Четверг', 'Пятница', 'Суббота');
  
  var dateObj = new Date(day_array[2], (day_array[1]-1), day_array[0]);
  
  return '<h4>'+day_array[0]+' '+russian_month[parseInt(day_array[1])]+'</h4></p><h5>'+russian_week[dateObj.getDay()]+'</h5>';
}

function check_total_price()
{  
//jQuery(document).ready(function () {
  
  if(document.getElementById('period')!=null)
  {  
  var field_period=document.getElementById('period').value;
  
  var basic_price=field_type_prices[document.getElementById('field_type').value];
  
  //edit-field-private-status-bussiness
  for (key in napt_jso)
  {
    
    if(document.getElementById('edit-field-private-status-'+key).checked==true)
    {
      var private_status=key;
      break;
    }
  }

  basic_price=basic_price+napt_jso[private_status];
 
  
  
  
  //
  var dates_price=field_periods[field_period];
  
  if(dates_price!=null)basic_price=basic_price+dates_price;
  
  var body_count=document.getElementById('body_counter').value;
  var ind=0;
  for(var j=0;j<count_limits.length;j++)
  {
    if(body_count>(count_limits[j]))
    {
      ind=j;
    }
    //last_element=count_limits[j];
  }
  
  if(ind)
  {  
  var delta=ind+1;
  basic_price=basic_price*delta;
  }
  if(document.getElementById("count_public_dates")!=null)document.getElementById("count_public_dates").value=body_count;
   
  if(document.getElementById('total_price'))document.getElementById('total_price').value=basic_price;
  }
//}); 
}

function set_period(period)
{

   if(period!=0)
   {
     
   document.getElementById('period_place').innerHTML='';  
   var div=document.createElement("div");
   div.innerHTML='Выбранно <span id="count_public_dates">0</span>дней, Осталось выбрать <span id="period_place_day">'+period+'</span> дней';
   document.getElementById('period_place').appendChild(div)
  document.getElementById('dates_tbl').style.display='table';
     var res=count_public_days();
     if(res<0)remove_last_dates(res);
     check_total_price();
   }else{
   document.getElementById('period_place').innerHTML='';  
   document.getElementById('dates_tbl').style.display='none';  
  }
   
}

function remove_last_dates(res)
{
  
  var inputs=document.getElementById("pub_dates").getElementsByTagName("input");
  var inputs_length=inputs.length-1;
  
  for(var i=inputs_length;i>(inputs_length+res);i--)
  {
  
    remove_date(inputs[i].value);
  }
}

/**
 * Validate Node FOrm
 */
function validate_advert_form()
{
  //chk body
  
  if(jQuery("#body").val().length<15)
  {
   jQuery("#body").attr('class',jQuery("#body").attr('class')+' errors');
   
    alert('Введено слишком мало содержания, Содержание важнейшая часть обьявления, расскажите пожалуйста чуточку больше о вашем предложении.');
    jQuery("#body").focus();
return false;
    
  }
  //chk offers
  
  if(jQuery('#advert_ajax_box table input').filter(':checked').val()==undefined)
  {
    alert('Нужно выбрать желаемое действие, варианты действий зависят от рубрик.');
    jQuery('#advert_ajax_box table').attr('class',jQuery('#advert_ajax_box table').attr('class')+' error');
    jQuery('#advert_ajax_box table').focus();
    return false;
  }
  //chk taxonomy
  if(jQuery('#loaded_taxonomy li').length==0)
  {
      jQuery('#edit-taxonomy-info').focus();
    jQuery('#edit-taxonomy-info').attr('class',jQuery('#edit-taxonomy-info').attr('class')+' error');
    jQuery('#edit-taxonomy-info').css('border','solid red 1px');
    alert('Обьязательно надо выбрать подходящие рубрики для публикации');
   
    return false;
      
    }
 //chk period
 
 if(jQuery("#period option:selected").index()==0)
 {
    alert('Выбирите подходящий вам период\цену и необходимые даты');
    jQuery("#period").focus();
    jQuery("#period").attr('class',jQuery("#period").attr('class')+' error');
    return false;
 }
 //chk public_dates   
 var count_dates=jQuery("#pub_dates input").length;
 
 if(count_dates<jQuery("#period option:selected").val())
 {
   alert('Выбирите необходимые даты, вам осталось выбрать ещё '+(document.getElementById("period").value-count_dates));
     jQuery("#period").focus();
    jQuery("#edit-fieldset-public-dates").css('border','solid red 1px');
    return false;
 }
 //chk phones
 if(jQuery('.form-item-field-phone-0 input').val().length==0)
 {
     alert('Впишите телефоны для связи');
     jQuery('.form-item-field-phone-0').focus();
    jQuery('.form-item-field-phone-0').css('border','solid red 1px');
    return false;
   
 }
 /*
 //chk social & email
 if(document.getElementById('edit-field-www').value.length>0)
 {
 if(document.getElementById('edit-field-www').value.substr(0,7)!='http://')
 {
   document.getElementById('edit-field-www').value='http://'+document.getElementById('edit-field-www').value;
   
 }  
 }
 if(document.getElementById('edit-field-social').value.length>0)
 {
 if(document.getElementById('edit-field-social').value.substr(0,7)!='http://')document.getElementById('edit-field-social').value='http://'.document.getElementById('edit-field-social').value;
 }*/
 //chk email
  var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
  
 if(jQuery('#edit-contacts-field-email').val().length>0)  
 { 
 if(reg.test(jQuery('#edit-contacts-field-email').val()) == false) 
  {
     alert('Ваш Email содержит ошибки, исправте пожалуйста');
    jQuery("#edit-contacts-field-email").focus();
    jQuery("#edit-contacts-field-email").css('border','solid red 1px');
    return false;
  }
 }
  return true;
}
/**
 *advert_node_form
 * Move taxonomy option record to some side
 **/
function chg_advert_taxonomy(input)
{
  //var inputs=document.getElementById("taxonomy_box").getElementsByTagName("input");
  if(input.checked==false)
  {
    jQuery('.opened_ul').append(jQuery('.cb'+input.id.substr(2)));
    if(jQuery('#loaded_taxonomy li').length==0)
    {
      jQuery('#advert_ajax_box').html('');
      
    }
  }else{
    
    jQuery('#loaded_taxonomy').append(jQuery('.cb'+input.id.substr(2)));
   
   if((jQuery('#advert_ajax_box').html()==null)||(jQuery('#advert_ajax_box').html().length==0)){ advert_load_form();}
  }
  
}
function advert_load_form(id)
{
  var nid=jQuery('#nid').val();
  var tids=new Array;
  
  jQuery('#loaded_taxonomy li').each(function(){
    tids[tids.length]=this.className.substr(2);
    
  });
  
    var url='/bt-form/callback/advert_form/'+tids+'/'+nid;
  
  jQuery.ajax({type: "GET",url: url}).done(function( msg ) {jQuery('#advert_ajax_box').html(msg);return null;});
 
}
function advert_load_car_model(id,title)
{
  var url='/bt-form/callback/advert_car_model/'+id+'|'+title;
  jQuery.ajax({type: "GET",url: url}).done(function( msg ) {jQuery('#car_models_box').html(msg);return null;});
}
function get_all_menu(offset_global)
{
  
  var menu=Array();
  jQuery('#advert_second_menu li input').each(function (){
    menu[menu.length]=this.id.substr(4);
  });
  var offers=Array();
  jQuery('#offers li input').each(function (){
    offers[offers.length]=this.id.substr(7,this.id.length-8);
  });

  var free_text=jQuery('.ym-searchfield').attr('value');
  
  var url=menu+"|"+offers+"|"+offset_global+((free_text.length)?"?free_text="+free_text:"");
  
  delete menu;delete offers;delete offset;delete free_text;
  return url;
}
function get_selected_menu(offset_global)
{
  
  var menu=Array();
  jQuery('#advert_second_menu li input:checked').each(function (){
    menu[menu.length]=this.id.substr(4);
  });
  var offers=Array();
  jQuery('#offers li input:checked').each(function (){
    offers[offers.length]=this.id.substr(7,this.id.length-8);
  });

  var free_text=jQuery('.ym-searchfield').attr('value');
  
  var url=menu+"|"+offers+"|"+offset_global+((free_text.length)?"?free_text="+free_text:"");
  
  delete menu;delete offers;delete offset;delete free_text;
  return url;
}
function reload_down_btn()
{
   
    var onclick=jQuery('.down').attr('onclick').substr(jQuery('.down').attr('onclick').length-4);
    var offset=parseInt(onclick.substr(0,onclick.indexOf(')')))+20;
    jQuery('.down').attr('onclick','load_adverts_next('+offset+');');
    
}
function load_adverts(tid)
{
var m;
//if(jQuery('#menu'+tid).attr('class')=='all')
if(jQuery('.all').attr('checked')=='checked')
{
m=get_all_menu(0);
}else{
m=get_selected_menu(0);
}
//if(m=='||0')m=tid;
 var url='/bt-form/callback/advert_load_adverts/'+m;
  
  jQuery.ajax({type: "GET",url: url}).done(function( msg ) {
  
    jQuery('#adverts').html(msg);
     switch_advert_view();
  // if(get_cookie('advert_view')!='list') resort_masonry();

  return null;
  
  });
  
}
/**
*When pressed more btn
**/
function load_adverts_next(offset)
{
var checkboxes;

if(jQuery('.all').attr('checked')=='checked')
 checkboxes=get_all_menu(offset);
else checkboxes=get_selected_menu(offset);
 var url='/bt-form/callback/advert_load_adverts/'+checkboxes;
  jQuery.ajax({type: "GET",url: url}).done(function( msg ) {
 
jQuery('.advert_row').append(msg);
//jQuery('.advert_row').append(msg).masonry();
  
//switch_advert_view();

//if(get_cookie('advert_view')!='list')jQuery('.advert_row').masonry('reload');					   

 
    if((msg.length>0)&&((offset+20)<parseInt(jQuery('.advert_counter span').text())))reload_down_btn();
    else  jQuery('.down').hide();	
  return null;    
  });
}
function switch_advert_view()
{
 if(get_cookie('advert_view')=='list')
    {
	set_row_view('pin');
      jQuery('#advert_view_btn').text("смотреть плитками");
    }else{
      set_tiles_view('pin');
    }

}
function set_row_view(classname)
{
 jQuery('.'+classname).css( 'display', 'block');
  jQuery('.'+classname).css( 'width', '95%');
  jQuery('.advert_row').attr( 'id','columns_in_row');
}
function set_tiles_view(classname)
{
jQuery('.'+classname).css( 'display', 'inline-block');
jQuery('.'+classname).css( 'width', '200px');
 jQuery('.advert_row').attr( 'id','columns');
}
function advert_openbox(id)
{
  if(document.getElementById(id).style.display=='none')
  {
    document.getElementById(id).style.display='block';
    
  }else{
    
    document.getElementById(id).style.display='none';
  }
  
}

function one_more(field,id,text)
{
  if(text==undefined)text='Ещё Телефон';
  
  var label=document.createElement("label");
  label.innerHTML=text;
  var inp=document.createElement("input");
  var inputs=document.getElementById(id).getElementsByTagName("input");
  
  inp.name=field+'['+(inputs.length+1)+']';
  inp.id=field+'['+(inputs.length+1)+']';
  inp.className='form-text';
  inp.type='text';
  var div=document.createElement("div");
  div.className='form-item form-type-textfield';
  div.appendChild(label);div.appendChild(inp);
  
  document.getElementById(id).appendChild(div);
}

function one_more_offer(field,id,name,oid,checked)
{
  
  var inputs=document.getElementById(id).getElementsByTagName("input");
  if(oid==null)oid='next'+(inputs.length+1);
  
  var chk=document.createElement("input");chk.type='checkbox';chk.name='oids_status['+oid+']';
  chk.checked=checked;
  
  var label=document.createElement("label");
  label.innerHTML='Предложение';
  
  var inp=document.createElement("input");
  inp.name=field+'['+oid+']';
  
  inp.id=field+'['+(inputs.length+1)+']';
  inp.className='form-text';
  inp.value=name;
  inp.type='text';
  
  var div=document.createElement("div");
  div.id='offer_'+oid;
  div.className='form-item form-type-textfield';
  div.appendChild(label);div.appendChild(chk);
  div.appendChild(inp);
  document.getElementById(id).appendChild(div);
}
function remove_offer(id,div_id)
{

  document.getElementById(id).removeChild(document.getElementById('div_id'));
}
//function advert_switch_menu(id)
function advert_switch_menu(tid)
{

  jQuery('.advert_menu_switcher h2').attr('class','');
  jQuery('#maincat'+tid).attr('class','active_switcher');
  
    var url='/bt-form/callback/advert_load_taxonomy/'+tid;

  jQuery.noConflict();
  jQuery.ajax({type: "GET",url: url}).done(function( msg ) { 	jQuery('#advert_taxonomy_box').html(msg);return null;});
}
/**
 * click on  main advert taxonomy - open menu
 **/
function open_advert_menu_box(tid)
{
  
  if(jQuery('#advert_subcat_box'+tid).html()=='')
  { jQuery('.advert_subcat_box').text('');
    jQuery('.advert_first_menu li').css('background','');
    jQuery('.advert_first_menu li').hide();
    
    var input=document.createElement('input');
    input.className='all';
    input.type='checkbox';
	input.id='menu'+tid;
    input.checked=true;
    input.onclick=function(){
    if(jQuery('.all').attr('checked')=='checked')
    {
	jQuery('#advert_subcat_box'+tid+' input').attr('checked',false);
	load_adverts(tid);
	//jQuery('#advert_subcat_box'+tid+' input').attr('checked',true);
    }else{
    jQuery('#advert_subcat_box'+tid+' input').attr('checked',false);
    }
      
    };
	
var img=document.createElement('img');
img.className='modal';
img.src='http://www.rozee.pk/i/employer/loader.gif.pagespeed.ce.fD9dhw4Xyi.gif';
jQuery('#advert_taxonomy_box').append(img);

    jQuery('#advert_first_item'+tid+' label').prepend(input);

	jQuery('#advert_first_item'+tid).show();
     var url='/bt-form/callback/advert_load_taxonomy/'+tid;
  jQuery.ajax({type: "GET",url: url}).done(function( msg ) { 
     jQuery('#advert_first_item'+tid).css('background','#F89F18');
	 jQuery('#advert_subcat_box'+tid).html(msg);
    //jQuery('#advert_subcat_box'+tid+' input').attr('checked',true);
   
    //jQuery('#advert_subcat_box'+tid+' input').attr('checked',true);
    load_adverts(tid);
	jQuery('.modal').remove();
  return null;
    
  });
  }else{
    jQuery('.all').remove();
   document.getElementById('advert_subcat_box'+tid).innerHTML=''; 
   jQuery('.advert_first_menu li').show();
   jQuery('.advert_first_menu li').css('background','');
  }
}
function advert_taxonomy_masonry()
{

//switch_advert_view();
if(get_cookie('advert_view')=='list')
	{
	set_row_view('pin');
 
  //jQuery('#masonry').masonry( 'destroy' );
	}else{ 


  set_tiles_view('pin'); 
/*jQuery('.advert_row').masonry({
    itemSelector : '.one_short_item',
    isResizable: false
  });*/
	}
}
function  chg_advert_dsg(element)
{
  var url;

  if(jQuery('.advert_row').attr('id')=='columns')
  {
    element.innerHTML='смотреть плитками'
    set_cookie('advert_view','list');
	set_row_view('pin');
  //jQuery('.advert_row').masonry('destroy');
  }else{
    element.innerHTML='смотреть списком';
   
    set_cookie('advert_view','tales');
	set_tiles_view('pin');
  }
}
function set_cookie ( name, value, exp_y, exp_m, exp_d, path, domain, secure )
{
  var cookie_string = name + "=" + escape ( value );
 
  if ( exp_y )
  {
    var expires = new Date ( exp_y, exp_m, exp_d );
    cookie_string += "; expires=" + expires.toGMTString();
  }
 
  if ( path )
        cookie_string += "; path=" + escape ( path );
 
  if ( domain )
        cookie_string += "; domain=" + escape ( domain );
  
  if ( secure )
        cookie_string += "; secure";
  
  document.cookie = cookie_string;
}
function get_cookie ( cookie_name )
{
  var results = document.cookie.match ( '(^|;) ?' + cookie_name + '=([^;]*)(;|$)' );
 
  if ( results )
    return ( unescape ( results[2] ) );
  else
    return null;
}
function change_advert_cat(tid,el)
{
  jQuery('.tabs a').attr('class','');
  el.className='active';
  jQuery('.advert_taxonomy_tbl').css('display','none');
  jQuery('#box'+tid).css('display','table');
}
function show_taxonomy(tid)
{
  
  if(jQuery('#taxo'+tid).attr('class')=='opened_ul')
  {
    if(jQuery('#loaded_taxonomy li').length>0)
    {
      jQuery('.msg_place').html('<h1 class="error">Сперва отмените выбранные категории, прежде чем закрывать</h1>');
      setTimeout(function(){jQuery('.msg_place').html('');},5000);
    }else{
  jQuery('#taxo'+tid).attr('class','');  
    jQuery('#taxo'+tid).hide();
    }
  }else{
    
    if(jQuery('#loaded_taxonomy li').length>0)
    {
      jQuery('.msg_place').html('<h1 class="error">Можно выбрать только подрубрики внутри одной и той же категории</h1>');
      setTimeout(function(){jQuery('.msg_place').html('');},5000);
    }else{
    //if(jQuery('.opened_ul').is(':hidden'))
    //{
    jQuery('#taxonomy_box ul').hide();  
    jQuery('#taxo'+tid).attr('class','opened_ul');  
    jQuery('#taxo'+tid).show();
    //}else{
    
    }
    //}
  }
}
function advert_node_left_search_submit()
{
  var options=new Array;
    jQuery('#advert_node_left_search select option:selected').each(function(){
      options[options.length]=this.value;
    });
    
    var url='/adverts/'+'?tid='+jQuery('#hidden_tid').val()+'&fields='+options;
    document.location=url;
}
/*#### afisha calendar #####*/

function redraw_years(year)
 {
 var a=0;
  jQuery('.tool_years a').each(function (){ 
  
  
  switch(a)
    {
    case 0:
      this.onclick=function(){changeYear((year-1));}
    break;
    case 1:
      this.onclick=function(){changeYear((year-1));}
      this.innerHTML=(year-1);
    break;
    case 2:
      this.onclick=function(){changeYear(year);}
      this.innerHTML=year;
    break;
    case 3:
      this.innerHTML=(year+1);
      this.onclick=function(){changeYear((year+1));}
    break;
    case 4:
      this.onclick=function(){changeYear((year+1));}
    break;
    }
  
  
  a++;
  });
   
 }
 function redraw_months(month)
 {
 var a=0;

  jQuery('.tool_months a').each(function (){ 
 
  switch(a)
    {
    case 0:
    if(month==0)
      this.onclick=function(){changeMonth(11);}
    else{ 
        
      this.onclick=function(){changeMonth((month-1));}
        }
    break;
    case 1:

    if(month==0)
    {
      this.onclick=function(){changeMonth(11);}
      this.innerHTML=monthNamesShort[11];
    }else{ 
      this.onclick=function(){changeMonth((month-1));}
      this.innerHTML=monthNamesShort[(month-1)];
      }
    break;
    case 2:
      this.onclick=function(){changeMonth(month);}
      this.id=month;
      this.innerHTML=monthNamesShort[month];
	  
    break;
    case 3:
    if(month==11)
    {
      this.onclick=function(){changeMonth(0);}
      this.innerHTML=monthNamesShort[0];
    }else{
      this.onclick=function(){changeMonth((month+1));}
	  
      this.innerHTML=monthNamesShort[(month+1)];
      }
    break;
    case 4:
    
   if(month==11)
    this.onclick=function(){changeMonth(0);}
   else
      this.onclick=function(){changeMonth((month+1));}
    break;
    }
  
  
  a++;
  });
 
 }
 function changeYear(year)
 {
 empty_active_th();
 var currentDate = jQuery( "#datepicker" ).datepicker( "getDate" );
 currentDate.setYear(year)
 
 jQuery( "#datepicker" ).datepicker( "setDate", currentDate );
  jQuery( ".tool_days a").attr('class','');
  redraw_years(year);
  
 }
 function empty_active_th()
 {
 for(var i=0;i<active_th.length;i++)delete(active_th[i]);
 for(var i=0;i<active_tt.length;i++)delete(active_tt[i]);
 }
 function changeMonth(month)
 {

 empty_active_th();
 
 var currentDate = jQuery( "#datepicker" ).datepicker( "getDate" );
 currentDate.setDate('01');
 currentDate.setMonth(month);
 
 jQuery( "#datepicker" ).datepicker( "setDate", currentDate );
  jQuery( ".tool_days a").attr('class','');
  redraw_months(month);
 }
 function add_date2collector(date,appy_btn)
 {
 if(appy_btn==null)appy_btn=true;
  if(jQuery('.'+date.split("/").join("_")).html()!=null)
   {
     jQuery('.'+date.split("/").join("_")).remove();
  }else{
   var inp=document.createElement('input');
   inp.type='hidden';
     //inp.type='text';
   inp.value=date;
   inp.className=date.split("/").join("_");
   
  jQuery('#datepicker_collector').append(inp); 
  }
 if(appy_btn)chk4apply_btn();
   //calendar_events_show();
  }
function add_date2collector_abc(date,active)
 {

  if(active==0)
   {
     jQuery('.'+date.split("/").join("_")).remove();
  }else{
  
  if(jQuery('.'+date.split("/").join("_")).html()==null)
  {
   var inp=document.createElement('input');
   inp.type='hidden';
   //inp.type='text';
   inp.value=date;
   inp.className=date.split("/").join("_");
   
  jQuery('#datepicker_collector').append(inp); 
  }
  }
  
  chk4apply_btn();
   //calendar_events_show();
  }
  var cal_btn_first_call=0;
 function chk4apply_btn()
 {
 
 var dates=get_dates();
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!

var yyyy = today.getFullYear();
if(dd<10){dd='0'+dd} if(mm<10){mm='0'+mm} today = yyyy+''+mm+''+dd;
 
 if((dates.length==1)&&(dates[0]==today))
 {
	jQuery('.cal_btn_apply').attr('class','cal_btn_apply');
  }else{
  jQuery('.cal_btn_apply').attr('class','cal_btn_apply cal_btn_active');
  }	
  
if(cal_btn_first_call==0)cal_btn_first_call++;
else {jQuery('.cal_btn_apply').show();
//jQuery('.tool_days a').removeClass('active_cal');
}


 }

  function set_click4th()
  {

  jQuery('.ui-datepicker-calendar tr th').each(function (n,th){
  jQuery(th).attr('class','');
  
  jQuery(th).click(function(){
  jQuery('.tool_days a').removeClass('active_cal');
  if(jQuery(th).attr('class')=='')
  {
	active_th[n]=n;
	jQuery(th).attr('class','active_cal');
  }else{
	delete(active_th[n]);
	jQuery(th).removeClass('active_cal');
	
  }

for(var i=0;i<dayNamesMin.length;i++)
    {  

     if(dayNamesMin[i]==this.getElementsByTagName('span')[0].innerHTML){numweek=i;break;}
    }

    if(numweek==0)numweek=7;

var weekday=1;
//var first=0
	 
	  jQuery('.ui-datepicker-calendar tr td').each(function (i,td){
	
	  if(weekday==numweek)
	  {
	      if(jQuery(td).find('.ui-state-default').html()!=null)
	      {
		  var d=get_calendar_day(jQuery(td).find('.ui-state-default').html());
                 
		  if(jQuery(th).attr('class')=='active_cal')
		  {
		
		   add_date2collector_abc(d,1);
		  }else{
		  add_date2collector_abc(d,0);
		  }
	    
	      jQuery('#datepicker').datepicker("setDate",d2date(d));
         
	      } 
		
	  }
	  
	  weekday++;
	  if(weekday==8){weekday=1;}
	  });
 
  });
	
	 
    });
//tut stroit ponedelniy	
weekly_choise_event();
//chk_past_days();

chk_week_days();
  }
  /*function chk_past_days()
  {
  var today=new Date();
  //var formated_date = today.format("yyyy-mm-dd");
 today= new Date(today.getFullYear(),prep_month(today.getMonth()),today.getDate(),'00','00');

    jQuery('.ui-datepicker-calendar tr td').each(function (i,td){
		 if(jQuery(jQuery(td).find('.ui-state-default').html()!=null))
		 {  
                     var d=get_calendar_day(jQuery(td).find('.ui-state-default').html());
                    var day= d2date(d);	
		  if(day.getTime()<today.getTime())
			{
			jQuery(td).addClass('opacity_day');
			}
		 }
	});
        
  }*/
  function get_calendar_day(d)
  {
    
      var m=jQuery('.tool_months .active_cal').attr('id');
      m=parseInt(m)+1; 
     var y=jQuery('.tool_years .active_cal').text();
     return prep_month(m)+'/'+prep_month(d)+'/'+y;
    
  }
  /**
  *Понедельное отмечание в календаре event 
  *тут задаётся когда в калндаре нажата '&#9668;' 
  **/
  function weekly_choise_event()
  {
  var rows_count=jQuery('.ui-datepicker-calendar tr').length-1;
  jQuery('.ui-datepicker-calendar tr').each(function (tri,tr){
      
//var tt=document.createElement('tt');
var tt1=jQuery('<tt>');

if(tri!=0)
{
rows_count--;
//tt.innerHTML='&#9668;';
tt1.html('&#9668;');

tt1.click(function (){
 jQuery('.tool_days a').removeClass('active_cal');   
 if(tt1.hasClass('active_cal'))
	{
		tt1.removeClass('active_cal');
		delete(active_tt[tri]);
	}else{
		tt1.addClass('active_cal');
		active_tt[tri]=tri;
	}  
        
  jQuery(tr).children('td').each(function(tdi,td){
      if(jQuery(td).find('.ui-state-default').html()!=null)
      {
          var d=get_calendar_day(jQuery(td).find('.ui-state-default').html());
	if(jQuery(tr).children('tt')[0].className=='active_cal')
	{
		add_date2collector_abc(d,1);
		td.className=td.className+' active_cal';
	}else{
		add_date2collector_abc(d,0);
		td.className='';
		}
               
		jQuery('#datepicker').datepicker("setDate", d2date(d));
      }    
});      



    
});
if(rows_count==0)tt1.css('borderBottomStyle','none');
jQuery(tr).append(tt1);
}else{
/*тут задаётся когда в калндаре нажата '*' */
tt1.text('ВСЕ');
//tt.innerHTML='ВСЕ';
tt1.click(function (){
if(tt1.hasClass('active_cal'))
        {
            tt1.removeClass('active_cal');
                    delete(active_tt[tri]);
            jQuery('.ui-datepicker-calendar th').removeClass('active_cal');       

            jQuery('.ui-datepicker-calendar tt').each(function (itt,ttt){
                    if(itt!=0)jQuery(ttt).removeClass('active_cal');  
            });
        }else{
            tt1.addClass('active_cal');
            active_tt[tri]=tri;
            jQuery('.ui-datepicker-calendar th').addClass('active_cal');

            jQuery('.ui-datepicker-calendar tt').each(function (itt,ttt){
                    if(itt!=0)jQuery(ttt).addClass('active_cal');
            });
        }
        jQuery('.ui-datepicker-calendar td').each(function (tdi,td){
            
     
       if(jQuery(td).find('.ui-state-default').html()!=null)
        {
          var d=get_calendar_day(jQuery(td).find('.ui-state-default').html());
                if(jQuery(tr).children('tt')[0].className=='active_cal')
                                {
  
                                if(jQuery(td.getElementsByTagName('a')[0]).html()!=null)add_date2collector_abc(d,1);
                                jQuery(td).addClass('active_cal');
                               
                                }else{
                                if(jQuery(td.getElementsByTagName('a')[0]).html()!=null)add_date2collector_abc(d,0);
                               
                                jQuery(td).removeClass('active_cal');
                                }
         }
        });

});
jQuery(tr).append(tt1);
delete(tt1);
}
});
  }
  function chk_week_days()
  {
  
  for(var i=0;i<8;i++)
	{

	  if(active_th[i]!=undefined)
		{
		jQuery('.ui-datepicker-calendar tr th').each(function (n,th)
			{
		if(n==i){jQuery(th).attr('class',jQuery(th).attr('class')+' active_cal');}
			});
		}
	}
	//4 gorizontal
	
	for(var tri=0;tri<(jQuery('.ui-datepicker-calendar tr').length);tri++)
		{
		
		if(active_tt[tri]!=undefined)
			{
			jQuery('.ui-datepicker-calendar tr').each(function (n,tr)
			{
				if(n>0)
				{
				
				if(n==tri){
					
					tr.getElementsByTagName('tt')[0].className='active_cal';
					}
				}
			});
			
			}
		
		}
	
	
  }
function chk_active_day(date)
{
  
var ddate=jQuery.datepicker.formatDate('mm_dd_yy', date); 
var today=new Date();
if(jQuery('.'+ddate).html()!=null)
    { 
        return [2,"active_cal"];
    }else{ 
      if(date.getTime()<today.getTime())
        {
        return [1,"past_cal"];
        }else{    
        return [1,""];
        }
    }
}
/*BTNs Yesterday,Today,Tommorow*/
function datepicker_set_d(d)
  {
      
   empty_active_th();
	jQuery('.tool_days a').each(function (){
	if(this.onclick.toString().substr(44,10)==d)
		{
		this.className='active_cal';
		}else{
		this.className='';
		}
	});
 
    var day=d2date(d);

		
	redraw_months(day.getMonth());
	//alert(dateParts[2]);
	redraw_years(day.getFullYear()); 
	//remove all
	jQuery('#datepicker_collector input').each(function(){
	jQuery(this).remove();
	});
    
    add_date2collector(d,false);
	
    jQuery('#datepicker').datepicker('setDate', day);
	// chk4apply_btn();
	//alert(jQuery('.cal_btn_apply').is(':hidden'));
	calendar_events_show();
  }
function datepicker_set_d_only(d)
  {
   empty_active_th();
	jQuery('.tool_days a').each(function (){
	if(this.onclick.toString().substr(44,10)==d)
		{
		this.className='active_cal';
		}else{
		this.className='';
		}
	});
  
    dateParts=d.split('/');
    
    var day=d2date(d);
	//alert(day.getMonth());
		
	redraw_months(day.getMonth());
	//alert(dateParts[2]);
	redraw_years(parseInt(dateParts[2])); 
	//remove all
	jQuery('#datepicker_collector input').each(function(){
	jQuery(this).remove();
	});
    
    add_date2collector(dateParts[0]+'/'+dateParts[1]+'/'+dateParts[2],false);
	
    jQuery('#datepicker').datepicker('setDate', day);
	// chk4apply_btn();
	//alert(jQuery('.cal_btn_apply').is(':hidden'));

  }
 function set_current_week(dates)
  {
  
   dates=dates.split(",");
  var today=new Date();
  var m=prep_month(today.getMonth()+1);
 dates.reverse();
  for(var i=0;i<dates.length;i++)
  {
	
   add_date2collector_abc(dates[i],1);
  //
	if(m==dates[i].substr(0,2))jQuery('#datepicker').datepicker('setDate', dates[i]);
  }
 
  
 
//calendar_events_show();
 jQuery('.cal_btn_apply').attr('class','cal_btn_apply');
 jQuery('.cal_btn_apply').hide();
 
  }
  /**
  *Event кнопки применить
  **/
  function calendar_events_show()
  {
 modal.close();
  var tids=new Array;
  
  jQuery('.places_one_cat a').each(function (){
  
  if(this.className.indexOf('active')!=-1)
	{
	
	var tid=this.className.substr(0,this.className.indexOf(' '));
	tid=tid.substr(tid.indexOf('_')+1);
	tids[tids.length]=tid;
	}
  });
  var dates=get_dates();
 
  var url='/bt-form/callback/spec_events_ajax/'+tids.join(",")+'|'+dates.join(",");

	switch_on_overlay();
	 jQuery('.cal_btn_apply').attr('class','cal_btn_apply');
	 jQuery('.cal_btn_apply').hide();
   jQuery.ajax({type: "GET",url: url}).done(function( msg ) {
   switch_off_overlay();
 
   jQuery('#masonry').html(msg);  

   });
  }
  function chk_dates()
  {
  return true;
  }
  function get_dates()
  {
  var dates=new Array;
  jQuery('#datepicker_collector input').each(function (){
  var dat=this.value.split('/');
	dates[dates.length]=dat[2]+dat[0]+dat[1];
  });
  return dates;
  }
function sc_cal()
{
var y=0;
var m=0;
if(!jQuery('.jcalendar').is(':hidden'))
	{
          
       jQuery('.ui-datepicker-calendar tr td').each(function(){
          
           if((jQuery(this).attr('data-year')!=null)&&(y==0))
               {
                 y=parseInt(jQuery(this).attr('data-year'));
               }
           if((jQuery(this).attr('data-month')!=null)&&(m==0))
               {
                 m=jQuery(this).attr('data-month');
               }     
          
       });

     
	jQuery('.jcalendar').hide();
	//el.innerHTML='v';
	jQuery('.v').addClass('x');
        jQuery('.v').removeClass('v');
       
  if(y>0)chg_buba(m,y);
        jQuery('.buba').show();
	}else{
	jQuery('.jcalendar').show();
	//el.innerHTML='x';
	jQuery('.x').addClass('v');
        jQuery('.x').removeClass('x');
         jQuery('.buba').hide();
	}
}
function strip_tags(txt)
{
 txt = txt.replace(/(<([^>]+)>)/ig,"");
 txt = txt.replace(/ /g,"");
 return txt;
}
function resize_thumbs()
{
 jQuery("div.thumb img").each(function()
	                {
	                    this.src = this.src.replace('100_100',
	                            '200_200');
	                });
}
function chk_opened(nid)
{
if(jQuery("#info"+nid).is(':hover')==false)
	{
	if(jQuery(".rec_thumb"+nid).is(':hidden'))
				{
				jQuery("#info"+nid).slideUp('slow');
				//jQuery(".rec_thumb"+nid).show('slow');
				jQuery(".rec_thumb"+nid).slideDown('slow');
				//jQuery("#info"+nid).hide('slow');
				
				resize_thumbs();
				
				}
	}else{
	setTimeout(function(){chk_opened(nid);},1000);
	}
}
function sw_com(n)
{
if(n=='fb')
	{
	//jQuery('.vk').hide('fast');
        jQuery('.vk').css('visibility','hidden');
        jQuery('.vk').css('height','0');
	//jQuery('.fb').show('fast');
        jQuery('.fb').css('visibility','visible');
        jQuery('.fb').css('height','200px');
	jQuery('.tabvk').removeClass("active_tab");
		jQuery('.tabfb').addClass("active_tab");
	}else{
	//jQuery('.fb').hide('fast');
        jQuery('.fb').css('visibility','hidden');
        jQuery('.fb').css('height','0');
	//jQuery('.vk').show('fast');
	 jQuery('.vk').css('visibility','visible');
          jQuery('.vk').css('height','200px');
	jQuery('.tabfb').removeClass("active_tab");
	jQuery('.tabvk').addClass("active_tab");
	}
}
function sw_events_in_place(n)
{
if(n=='future')
	{
	jQuery('.past_events').hide('fast');
	jQuery('.future_events').show('fast');

	jQuery('.tabepp').removeClass("active_tab");
	jQuery('.tabepf').addClass("active_tab");
	}else{
	jQuery('.future_events').hide('fast');
	jQuery('.past_events').show('fast');
	
	jQuery('.tabepf').removeClass("active_tab");
	jQuery('.tabepp').addClass("active_tab");
	}
}
function sw_placenode(n)
{
switch(n)
	{
	case 'info':
	
	jQuery('.placedescription').hide();
	jQuery('.gallery_list_wrapper').hide();
        jQuery('.other_places').hide();
	jQuery('.comments').hide();
	jQuery('.info_thumb').show();
	jQuery('.tab_description').removeClass("active_tab");
	jQuery('.tab_gallery').removeClass("active_tab");
	jQuery('.tab_comments').removeClass("active_tab");
         jQuery('.tab_other_places').removeClass("active_tab");
	jQuery('.tab_info').addClass("active_tab");
	break;
	case 'gallery':
	jQuery('.comments').hide();
	jQuery('.placedescription').hide();
        jQuery('.other_places').hide();
	jQuery('.info_thumb').hide();
	jQuery('.gallery_list_wrapper').show();
	jQuery('.tab_description').removeClass("active_tab");
	jQuery('.tab_info').removeClass("active_tab");
	jQuery('.tab_comments').removeClass("active_tab");
         jQuery('.tab_other_places').removeClass("active_tab");
	jQuery('.tab_gallery').addClass("active_tab");
	break;
	case 'description':
	jQuery('.comments').hide();	
	jQuery('.info_thumb').hide();
	jQuery('.gallery_list_wrapper').hide();
         jQuery('.other_places').hide();
	jQuery('.placedescription').show();
	jQuery('.tab_gallery').removeClass("active_tab");
	jQuery('.tab_info').removeClass("active_tab");
	jQuery('.tab_comments').removeClass("active_tab");
         jQuery('.tab_other_places').removeClass("active_tab");
	jQuery('.tab_description').addClass("active_tab");
	break;
	case 'comments':
	jQuery('.placedescription').hide();	
	jQuery('.info_thumb').hide();
	jQuery('.gallery_list_wrapper').hide();
        jQuery('.other_places').hide();
	jQuery('.comments').show();
	jQuery('.tab_gallery').removeClass("active_tab");
	jQuery('.tab_info').removeClass("active_tab");
	jQuery('.tab_description').removeClass("active_tab");
        jQuery('.tab_other_places').removeClass("active_tab");
	jQuery('.tab_comments').addClass("active_tab");
	break;
        case 'other_places':
        jQuery('.placedescription').hide();	
	jQuery('.info_thumb').hide();
	jQuery('.gallery_list_wrapper').hide();
	jQuery('.comments').hide();
        jQuery('.other_places').show();
	jQuery('.tab_gallery').removeClass("active_tab");
	jQuery('.tab_info').removeClass("active_tab");
	jQuery('.tab_description').removeClass("active_tab");
	jQuery('.tab_comments').removeClass("active_tab");
        jQuery('.tab_other_places').addClass("active_tab");
        break;
	}
}
function switch_on_overlay()
{
var div=document.createElement('div');
div.id='animatediv';
div.innerHTML='<div class="loading">Идет поиск событий</div>';
//div.style.height=jQuery('.box_content').css('height');
div.style.height='100%';
jQuery('.box_content').append(div);
}
function switch_off_overlay()
{
jQuery('#animatediv').remove();
}
function add_lnk4remove_event_filters()
{
if(jQuery('.remove_filters_lnk').html()==null)
{ 
var a=document.createElement('div');
a.className='remove_filters_lnk';
a.innerHTML='Сбросить всё';
	a.onclick=function(){
		jQuery('.places_one_cat a').each(function (){
		jQuery(this).removeClass('active');
		});
	jQuery('.remove_filters_lnk').remove();
	}
jQuery(".places_one_cat").append(a);
}
}
function chk4remove_event_filters_lnk()
{
var was=false;
jQuery('.places_one_cat a').each(function (){
if(jQuery(this).attr('class').indexOf('active')>-1)was=true;			
});
if(was==false)jQuery('.remove_filters_lnk').remove();
}

var modal = (function(){
    var 
    method = {},
   
    $modal,
    $content,
    $close;

    // Append the HTML

    // Center the modal in the viewport
    method.center = function () {
	 var top, left;

    top = Math.max(jQuery(window).height() - $modal.outerHeight(), 0) / 2;
    left = Math.max(jQuery(window).width() - $modal.outerWidth(), 0) / 2;

    $modal.css({
        top:top + jQuery(window).scrollTop(), 
        left:left + jQuery(window).scrollLeft()
    });
	};

    // Open the modal
    method.open = function (settings) {
		$content.empty().append(settings.content);

    $modal.css({
        width: settings.width || 'auto', 
        height: settings.height || 'auto'
    })

    method.center();

    jQuery(window).bind('resize.modal', method.center);

    $modal.show();
  
	};

    // Close the modal
    method.close = function () {
	 $modal.hide();
   
    $content.empty();
    jQuery(window).unbind('resize.modal');
	};

	

$modal = jQuery('<div id="modal"></div>');
$content = jQuery('<div id="content1"></div>');
$close = jQuery('<a id="close" href="#">close</a>');
$close.click(function(e){
    e.preventDefault();
    method.close();
});

$modal.hide();

$modal.append($content, $close);

jQuery(document).ready(function(){
    //jQuery('body').append($overlay, $modal);
	jQuery('body').append($modal);
});

    return method;
}());

function order_ticket_form(nid)
{
jQuery.get('/order_ticket.php?nid='+nid, function(data){
					modal.open({content: data, width: "590px"});
				});
 click4modal_close();
}
function video_modal(VIDEO_ID,type,title)
{
   
    var width=600;
    var height=360;
    var html='';
    if(type=='youtube')
        {
             html='<iframe class="youtube-player" type="text/html" width="100%" height="600" src="http://www.youtube.com/v/'+VIDEO_ID+'" allowfullscreen frameborder="0"></iframe>';
        }else if(type=='vimeo')
         {
             html='<iframe src="//player.vimeo.com/video/'+VIDEO_ID+'" width="'+width+'" height="'+height+'" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>'; 
         }   
    modal.open({content: '<div class="videomodal">'+html+'</div>', width: "620px"});
    click4modal_close();
       				

}
function click4modal_close(){
    var firstClick = true;
        jQuery(document).bind('click.myEvent', function(e) {
            if (!firstClick && jQuery(e.target).closest('#modal').length == 0) {
                 modal.close();
                jQuery(document).unbind('click.myEvent');
             }
            firstClick = false;
        });
    
}
function submit_order()
{

if(document.order.phone.value.length==0)
{
alert('Необходим ваш номер телефона для заказа!');
document.order.phone.focus();
return false;
}
if(document.order.phone.value.substr(0,3)!='+38')
{
alert('Можно оставлять только номера телефонов в Украине');
document.order.phone.focus();
return false;
}
if(document.order.phone.value.length!=13)
{
alert('Номер телефона неверный');
document.order.phone.focus();
return false;
}
if(!(parseInt(document.order.phone.value.substr(3))>0))
{
alert('Номер телефона неверный! Попробуйте цифры');
document.order.phone.focus();
return false;
}

jQuery.ajax({
type: "POST",
url: "/order_ticket.php?nid="+document.order.nid.value+'&date='+document.order.tdate.value,
data: { name: document.order.name.value, phone: document.order.phone.value,date:document.order.date.value },
success: function(answer){modal.open({content: answer, width: "500px", height: "200px"});},
dataType: 'html'
});
}
function open_place_menu(element,tid)
{
if(jQuery('.category'+tid).is(':hidden')==false)
	{
	
	jQuery(element).removeClass('cat_op');
	jQuery(element).addClass('cat_cl');
	jQuery('.category'+tid).hide('fast');
	}else{
	jQuery(element).removeClass('cat_cl');
	jQuery(element).addClass('cat_op');
	jQuery('.category'+tid).show('fast');
	}
}
function close_filters()
{
			jQuery('.filters').hide();
			jQuery('.middle').css('margin-left','150px');
			jQuery('.box_content').before('<a href="javascript://" onclick="open_filters()" class="filters_btn">&nbsp;</a>');
			jQuery('.box_content').addClass('then_closed_filter');
			
			
}
function open_filters()
{
	jQuery('.middle').css('margin-left','');
	jQuery('.filters').show();
	jQuery('.filters_btn').remove();
	jQuery('.box_content').removeClass('then_closed_filter');
	set_cookie('filters_btn',0);
}
function show_places_list()
{
if(jQuery('#columns').is(':hidden'))
	{
	jQuery('#columns_inline').remove();
	jQuery('#columns').show();
	jQuery('.places_list_btn').html('Смотреть списком');
	}else{
		
		jQuery('#columns').after('<div id="columns_inline"></div>');
		jQuery('#columns .pin').each(function(){
		
              // jQuery(this).find('.afishes_count').text()
              
		jQuery('#columns_inline').append('<div><a href="'+jQuery(this).find('h2 a').attr('href')+'">'
                        +jQuery(this).find('h2 a').html()+'. '						+((jQuery(this).find('.city_link').html()!=undefined)?jQuery(this).find('.city_link').html():'')
                        +((jQuery(this).find('h2 img').attr('id')=='place_with_event')?'<img src="'+jQuery(this).find('h2 img').attr('src')+'" id="'+jQuery(this).find('h2 img').attr('id')+'" title="'+jQuery(this).find('h2 img').attr('title')+'">':'')
                        
                        +((jQuery(this).find('.afishes_count').text().length>0)?'  <div class="eventdate place_month_count"> '+jQuery(this).find('.afishes_count').text()+'</div>':'')
                        +'</a>'
                        +'</div>');					
		});
		jQuery('#columns').hide();
		jQuery('.places_list_btn').html('Смотреть плитками');
	}
}

function hightlight_ticket(id)
{
jQuery('.od').removeClass("active_ticket");
jQuery('.schedule'+id).addClass("active_ticket");
}
function hightlight_thumb(id)
{
jQuery('.thumbli').hide()
jQuery('.thumb'+id).show();
}
function other_opn(tid)
{
    if(jQuery('.other_block'+tid).is(':hidden')==true)
        {
         jQuery('.other_block'+tid).show();   
         jQuery('.other_ticket'+tid).addClass('other_ticket_opened');
        }else{
           jQuery('.other_block'+tid).hide();  
           jQuery('.other_ticket'+tid).removeClass('other_ticket_opened');
        }
}
var last_cho_year=0;
function select_all_tt(month,year)
{
    
    //change buba code
    chg_buba(month,year);
    jQuery('#middle_tool').attr('class','active_cal');
    //remove old choose
   calendar_events_clear();
   //change month
    //new choose
    var weekday=1;
      jQuery('.ui-datepicker-calendar tr td').each(function (i,td){
	     if(jQuery(td).find('.ui-state-default').html()!=null)
	      {
		
                  var d=get_calendar_day(jQuery(td).find('.ui-state-default').html());
                jQuery(td).addClass('active_cal');
              add_date2collector_abc(d,1);
	     } 
	
	  
	  weekday++;
	  if(weekday==8){weekday=1;}
	  });
          
          //set active headers
            jQuery('.ui-datepicker-calendar tr tt').each(function(){jQuery(this).addClass('active_cal');});
             jQuery('.ui-datepicker-calendar tr th').each(function(){jQuery(this).addClass('active_cal');});
          //get request      
 calendar_events_show();
 last_cho_year=year;
}
function chg_buba(month,year)
{
    month=parseInt(month);
    var nm;
     var ny=parseInt(year);
    // alert(ny);
    jQuery('.buba a').each(function(i,a){
        
    switch(i)    
        {
        case 0:
            nm=(month-1);
            
            if(nm<0){nm=11;ny=year-1;}
            //jQuery(a).attr('onclick','select_all_tt('+nm+','+ny+');');  
            jQuery(a).attr('onclick','chg_buba('+nm+','+ny+');');  
        break;    
        case 1:
            nm=(month-1);
            if(nm<0){nm=11;ny=year-1;}
             jQuery(a).attr('onclick','select_all_tt('+nm+','+ny+');');  
             jQuery(a).html(monthNamesShort[nm]);
        break;
        case 2:
            jQuery(a).attr('class','');
          jQuery(a).attr('onclick','select_all_tt('+(month)+','+year+');');   
          jQuery(a).html(monthNamesShort[(month)]);
        break;    
        case 3:
            nm=month+1;
            if(nm>11){nm=0;
            //    ny=year+1;
            }
           // console.log('Year is '+ny);
         jQuery(a).attr('onclick','select_all_tt('+nm+','+((nm==0)?(year+1):year)+');');   
         jQuery(a).html(monthNamesShort[nm]);
        break;
        case 4:
             nm=month+1;
             if(nm>11){nm=0;
              //   ny=year+1;
             }
          // jQuery(a).attr('onclick','select_all_tt('+nm+','+ny+');'); 
           jQuery(a).attr('onclick','chg_buba('+nm+','+((nm==0)?(year+1):year)+');'); 
        break;
        }
    });
      changeMonth(month);
       changeYear(year);
}
function calendar_events_clear()
{
    //remove old choose
    jQuery('.ui-datepicker-calendar tr td').each(function(i,td){
        jQuery(td).removeClass('active_cal');
        var d=get_calendar_day(jQuery(td).find('ui-state-default').html());
         
        add_date2collector_abc(d,0);
    });
   jQuery('#datepicker_collector').html('');
   
    //unset active headers
            jQuery('.ui-datepicker-calendar tr tt').each(function(){jQuery(this).removeClass('active_cal');});
             jQuery('.ui-datepicker-calendar tr th').each(function(){jQuery(this).removeClass('active_cal');});
}
function ib_rebuild()
{
   
   jQuery('#internet-bilet-55800 table').hide();
    jQuery('#internet-bilet-55800 table tr td').each(function (){
        var links=new Array;
        jQuery(this).find('a').each(function (aid,alink){
        links.push(jQuery(alink));  
        });
       
         var bs=new Array;
        jQuery(this).find('b').each(function (bid,bb){
        bs.push(jQuery(bb).html());  
        });
        
         var tbl=jQuery('<table>');
        tbl.attr("class","oneplaceticket");
        
        var tr=jQuery('<tr>');
        var td=jQuery('<td>');
        if(links.length==2)
        {    
        td.append('<div class="zonename">'+links[0].html()+'</div>');
        td.append('осталось <b>'+bs[1]+'</b> билетов');
          var td2=jQuery('<td>');
          td2.attr('align','right');
          
          td2.append('<a class="order_tickets_but" onclick="_gaq.push([\'_trackEvent\', \'buy_ticket\', \'way_of_buying\', \'inetbilet\']);" target="_blank" href="'+links[1].attr('href')+'">Купить билет</a>');
          td2.append('<div class="oneplaceticket_price">'+bs[0]+'</div>');
        }else{
           td.append('<div class="zonename"></div>');
          td.append('осталось <b>'+bs[1]+'</b> билетов');
          var td2=jQuery('<td>');
          td2.attr('align','right');
         
          td2.append('<a class="order_tickets_but" onclick="_gaq.push([\'_trackEvent\', \'buy_ticket\', \'way_of_buying\', \'inetbilet\']);" target="_blank" href="'+links[0].attr('href')+'">Купить билет</a>');
          td2.append('<div class="oneplaceticket_price">'+bs[0]+' грн.</div>');   
        }
        tr.append(td);
        tr.append(td2);
        tbl.append(tr);
        jQuery('#internet-bilet-55800').append(tbl);
    });
 // table+='</table>'; 

//jQuery('#internet-bilet-55800 table').remove();
  //jQuery('#internet-bilet-55800').empty().append(tbl);

   //jQuery('#internet-bilet-55800').html(table);
   
    
}
function chk_ib()
{
    if(jQuery('#internet-bilet-55800 table').html()!=null)
        {
           ib_rebuild();
        }else{
            setTimeout(function (){chk_ib()}, 1000); 
        }
}
function load_first_buba()
{
    jQuery('.buba span').each(function (){
    var a=jQuery('<a>');
    a.attr('onclick',jQuery(this).attr('onclick'));
    a.attr('class',jQuery(this).attr('class'));
    a.attr('href','javascript://');
    a.attr('id',jQuery(this).attr('id'));
    a.html(jQuery(this).html());
    
    jQuery(this).remove();
    jQuery('.buba').append(a);
    });
}
function event_tooltip(el,src,text)
{
   
     jQuery(el).tooltip({
hide: { effect: "slideUp", duration: 100 } ,
content: function() {  return "<div class='tooltipbox'><div class=''><img src='"+src+"'></div></div>";}
});

}
function show_box(el,linkel)
{ 
 
    if(jQuery(el).is(':hidden'))
    {
        jQuery(el).show();
        //jQuery(linkel).addClass('expanded');
         jQuery(linkel).addClass('other_ticket_opened');
    }else{
         jQuery(linkel).removeClass('other_ticket_opened');
      //   jQuery(linkel).removeClass('expanded');
      jQuery(el).hide();  
    }
}
var vidli=new Array;

function get_max_vidli(c,max2display)
{

     jQuery('.'+c+' li').each(function (i,li){
       
     });
    
     return Math.ceil(i/max2display);
}
function roll_video (c,act,max2display)
{
     if(vidli[c]=='undefined')vidli[c]=0;
    if(act=='next')vidli[c]++;
    else if(act=='prev')vidli[c]--;
     
   if(jQuery('.'+c+' .vidli'+vidli[c]).html()==null)
    {   
  
    if(act=='next')vidli[c]=0;
    else if(act=='prev')vidli[c]=get_max_vidli(c,max2display)-1;
        //return null;
    }
   
     var options_hide = {};
     var options_show = {};
    
    if(act=='next'){
        options_hide['direction']='right';
        options_show['direction']='left';
    }else{ 
        
        options_hide['direction']='left';
        options_show['direction']='right';
        
    }
    jQuery(c).hide('slide',options_hide,100);
    
   
    jQuery('.'+c+' li').each(function (i,li){
    if(jQuery(li).hasClass('vidli'+vidli[c])==false)
       {
         //  .hide( selectedEffect, options, 1000, callback );
            jQuery(li).hide();
       }else{
            jQuery(li).show();
       }
    });
   jQuery(c).show('slide',options_show,100);
}
function reload_vimeo(im)
{
    var url=jQuery('.'+im).attr('src');
    var result=null;
   
    jQuery.getJSON(url, function( data ) {
       
               jQuery.each( data[0], function( key, val ) {
                   if(key=='thumbnail_medium')
                    {
                      
                        jQuery('.'+im).attr('src',val);
                    }
                //items.push( "<li id='" + key + "'>" + val + "</li>" );
                });
                });
}

function init_scroll_timer(c,max2display,period,evt_el)
{
    jQuery('.'+c).timer({
		delay: period,
		repeat: true,
		autostart: true,
		callback: function( index ) {
                 
			 roll_video(c,'next',max2display);
		}
	});
    
    jQuery('.'+evt_el).mouseenter(function(){jQuery('.'+c).timer('pause');}).mouseleave(function(){jQuery('.'+c).timer('resume');});
}
var places_page=0;
function get_more_places()
{
        $.ajax({
                type: "GET",
                url: 'bt-form/callback/spec_places_ajax/'+places_page+'/'+$( window ).width()
               
            }).done(function( msg ) {
                if(msg.length==0)
                {
                 jQuery('.places_more').remove();
                 jQuery('#places_more_box').append('<div class="itsall">Всё</div>');
                // jQuery('#columns').append('<div class="itsall">Всё</div>');
                }else{    
                places_page++;
               // jQuery('#columns').append(msg);
                jQuery('#places_more_box').append(msg);
                }
            });
}